package com.gy.api.pc.ykz.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.xxpt.gateway.shared.api.request.OapiGettokenJsonRequest;
import com.alibaba.xxpt.gateway.shared.api.request.OapiMessageWorkNotificationRequest;
import com.alibaba.xxpt.gateway.shared.api.request.OapiRpcOauth2DingtalkAppTokenJsonRequest;
import com.alibaba.xxpt.gateway.shared.api.request.OapiTcV2OpenapiTaskCreateJsonRequest;
import com.alibaba.xxpt.gateway.shared.api.response.OapiGettokenJsonResponse;
import com.alibaba.xxpt.gateway.shared.api.response.OapiMessageWorkNotificationResponse;
import com.alibaba.xxpt.gateway.shared.api.response.OapiRpcOauth2DingtalkAppTokenJsonResponse;
import com.alibaba.xxpt.gateway.shared.api.response.OapiTcV2OpenapiTaskCreateJsonResponse;
import com.alibaba.xxpt.gateway.shared.client.http.ExecutableClient;
import com.alibaba.xxpt.gateway.shared.client.http.IntelligentPostClient;
import com.gy.api.base.Type;
import com.gy.api.pc.ykz.domain.OapiRpcAuth2UserInfo;
import com.gy.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class IntelligentPostService {

	private final static String GET_TOKEN = "/gettoken.json";
	private final static String GET_USER_INFO = "/rpc/oauth2/dingtalk_app_user.json";
	private final static String SEND_MESSAGE = "/message/workNotification";
	private final static String SEND_TODO = "/tc/v2/openapi/task/create.json";

	public final static String TOKEN_KEY = "ykz:auth:token";

	public final static String TICK_KEY = "ykz:auth:token";

	private static ExecutableClient executableClient;
	@Value("${ykz.auth.domainName}")
	public String domainName;
	@Value("${ykz.auth.protocol}")
	public String protocol;
	@Value("${ykz.auth.appKey}")
	public String appKey;
	@Value("${ykz.auth.appSecret}")
	public String appSecret;

	@Autowired
	protected RedisTemplate<String, String> redisTemplate;

	@PostConstruct
	public void init() {
		executableClient = ExecutableClient.getInstance();
		// DomainName不同环境对应不同域名，渝快政使用下面示例, 政务外网需要查看接口必读完成配置
		executableClient.setDomainName(domainName);
		executableClient.setProtocal(protocol);
		// 应用App Key
		executableClient.setAccessKey(appKey);
		// 应用App Secret
		executableClient.setSecretKey(appSecret);
		executableClient.init();
	}

	public String getToken() {
		String accessToken = redisTemplate.opsForValue().get(TOKEN_KEY);
		if (!StringUtils.isEmpty(accessToken)) {
			if (log.isDebugEnabled()) {
				log.debug("缓存 accessToken 存在使用缓存 accessToken：{}", accessToken);
			}
			return accessToken;
		}
		// executableClient保证单例
		IntelligentPostClient intelligentGetClient = executableClient.newIntelligentPostClient(GET_TOKEN);
		OapiGettokenJsonRequest oapiGettokenJsonRequest = new OapiGettokenJsonRequest();
		// 获取结果
		OapiGettokenJsonResponse apiResult = intelligentGetClient.post(oapiGettokenJsonRequest);
		log.info("getToken:{}", apiResult);
		log.info("getMessage:{}", apiResult.getMessage());
		log.info("getCode:{}", apiResult.getCode());
		log.info("getContent:{}", apiResult.getContent());
		if(apiResult.getContent()==null){
			throw new BusinessException(Type.FAIL.getCode(),apiResult.getMessage());
		}
		String dataStr = apiResult.getContent().getData();
		JSONObject data = JSON.parseObject(dataStr);
		accessToken = data.getString("accessToken");
		Integer expiresIn = data.getIntValue("expiresIn");
		// 设置redis缓存
        redisTemplate.opsForValue().set(TOKEN_KEY, accessToken, expiresIn, TimeUnit.SECONDS);
		return accessToken;
	}

	public OapiRpcAuth2UserInfo getUserInfo(String code, String token) {
		// executableClient保证单例
		IntelligentPostClient intelligentGetClient = executableClient.newIntelligentPostClient(GET_USER_INFO);
		OapiRpcOauth2DingtalkAppTokenJsonRequest oapiGetUserInfoReq = new OapiRpcOauth2DingtalkAppTokenJsonRequest();
		// 登录access_token
		oapiGetUserInfoReq.setAccess_token(token);
		// 临时授权码
		oapiGetUserInfoReq.setAuth_code(code);
		OapiRpcOauth2DingtalkAppTokenJsonResponse  apiResult = intelligentGetClient.post(oapiGetUserInfoReq);
		log.info("resp:\n" + apiResult.getContent());
		String dataStr = apiResult.getContent();
		String data = JSON.parseObject(dataStr).getJSONObject("content").getString("data");
		OapiRpcAuth2UserInfo userInfo = JSON.parseObject(data, OapiRpcAuth2UserInfo.class);
		log.info("getUserInfo:" + userInfo);

		return userInfo;
	}

//	/**
//	 * 发送消息
//	 * @param msg
//	 * @param accoundIds 接收人用户ID(accountId)， 多个人时使用半角逗号分隔
//	 * @return
//	 */
//	public String workNotification(YKZMessageDTO message, String accoundIds) {
//		// executableClient保证单例
//		IntelligentPostClient intelligentGetClient = executableClient.newIntelligentPostClient(SEND_MESSAGE);
//		OapiMessageWorkNotificationRequest oapiMessageWorkNotificationRequest = new OapiMessageWorkNotificationRequest();
//        //接收者的部门id列表
//        //oapiMessageWorkNotificationRequest.setOrganizationCodes("字符串");
//        //接收人用户ID 接收人用户ID(accountId)， 多个人时使用半角逗号分隔
//        oapiMessageWorkNotificationRequest.setReceiverIds(accoundIds);
//        //租户ID
//        oapiMessageWorkNotificationRequest.setTenantId("1");
//        //业务消息id
//        oapiMessageWorkNotificationRequest.setBizMsgId(UUID.randomUUID().toString());
//        //消息对象 {“msgtype”:“text”,“text”:{“content”:“消息内容”}}
//        JSONObject msg = new JSONObject();
//        msg.put("msgtype", message.getMessageType());
//        if ("link".equals(message.getMessageType())) {
//        	JSONObject link = new JSONObject();
//            link.put("messageUrl", message.getMessageUrl());
//            link.put("text", message.getText());
//            link.put("title", message.getTitle());
//            msg.put("link", link);
//        } else if ("markdown".equals(message.getMessageType())) {
//        	JSONObject markdown = new JSONObject();
//        	markdown.put("text", message.getText() + ", 链接："  + message.getMessageUrl());
//        	markdown.put("title", message.getTitle());
//            msg.put("markdown", markdown);
//        } else {
//        	JSONObject text = new JSONObject();
//        	text.put("content", message.getText() );
//        	msg.put("text", text);
//        }
//
//        oapiMessageWorkNotificationRequest.setMsg(msg.toJSONString());
//        //获取结果
//        OapiMessageWorkNotificationResponse apiResult = intelligentGetClient.post(oapiMessageWorkNotificationRequest);
//        log.info("消息发送结果：" + apiResult.getContent());
//        return apiResult.getContent();
//	}
//
//	public String todo(OapiTcV2OpenapiTaskCreateJsonRequest todoTask) {
//		IntelligentPostClient intelligentGetClient = executableClient.newIntelligentPostClient(SEND_TODO);
//        //获取结果
//        OapiTcV2OpenapiTaskCreateJsonResponse apiResult = intelligentGetClient.post(todoTask);
//        log.info("消息发送结果：" + apiResult.getMessage() + ",code:" + apiResult.getBizErrorCode());
//        if (apiResult.getContent() == null) {
//        	return apiResult.getMessage();
//        }
//        return apiResult.getContent().getData();
//	}

}
